﻿using System;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Ink;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;
using System.IO;

namespace System.Windows.Media.DirectShow.Filters
{
    public class WaveSourceParser : MediaSourceAsync
    {

        private WaveSourceParserOutputPin _outputPin;
        internal const int HeaderSize = 44;
        private WaveFormatExtensible format;
        private int dataSize;
        private long offset;

        public WaveSourceParser()
        {

        }

        public override string Name
        {
            get { return "Wave Parser"; }
        }

        internal WaveSourceParserOutputPin OutputPin
        {
            get { return _outputPin; }
        }

        protected override void OnStreamAvailable(Stream stream)
        {
            base.OnStreamAvailable(stream);

            this.ParseHeader(stream);
            this.SetFormat(format);
        }

        private void ParseHeader(Stream stream)
        {
            if (stream.Length < HeaderSize)
                throw new InvalidDirectShowMediaTypeException("Invalid file header");

            BinaryReader reader = new BinaryReader(stream);

            format = new WaveFormatExtensible();
            reader.ReadInt32(); // "RIFF" file description header
            int size = reader.ReadInt32();
            reader.ReadInt32(); // "WAVE" description header
            reader.ReadInt32(); // "fmt " description header
            int formatSize = reader.ReadInt32();
            if (formatSize != 16)
                throw new InvalidDirectShowMediaTypeException("Unknown format type");
            format.FormatTag = reader.ReadInt16(); // WAVE type format
            format.Channels = reader.ReadInt16();
            format.SamplesPerSec = reader.ReadInt32();
            format.AverageBytesPerSecond = reader.ReadInt32();
            format.BlockAlign = reader.ReadInt16();
            format.BitsPerSample = reader.ReadInt16();
            reader.ReadInt32(); // "data" description header
            dataSize = reader.ReadInt32(); // size of data chunk
        }

        private void SetFormat(WaveFormatExtensible format)
        {
            AMMediaType mediaType = new AMMediaType
            {
                MajorType = MediaMajorTypes.Audio,
                SubType = MediaSubTypes.PCM,
                FixedSizeSamples = true,
                Format = format,
                SampleSize = format.SamplesPerSec
            };

            _outputPin = new WaveSourceParserOutputPin(this, mediaType);
            this.Pins.Add(_outputPin);
        }

    }
}
